// 导入钩子函数 vue-router
import { createRouter, createWebHistory } from 'vue-router'
// 导入钩子函数 axios
import axios from 'axios'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Signup from '@/views/Signup.vue'
import ColumnDetail from '@/views/ColumnDetail.vue'
import CreatePost from '@/views/CreatePost.vue'
import PostDetail from '@/views/PostDetail.vue'
import store from '@/assets/js/store'

// 页面路由 - 哈希规则
const routerHistory = createWebHistory()

// 页面路由 - 规则设置
const router = createRouter({
  history: routerHistory,
  routes: [{
    // url路径
    path: '/',
    // 页面名称
    name: 'home',
    // 页面组件
    component: Home
  }, {
    path: '/login',
    name: 'login',
    component: Login,
    meta: { redirectAlreadyLogin: true }
  }, {
    path: '/signup',
    name: 'signup',
    component: Signup,
    meta: { redirectAlreadyLogin: true }
  }, {
    path: '/column:id',
    name: 'column',
    component: ColumnDetail
  }, {
    path: '/create',
    name: 'create',
    component: CreatePost,
    meta: { requiredLogin: true }
  }, {
    path: '/posts/:id',
    name: 'post',
    component: PostDetail
  }]
})

// 前置守卫
router.beforeEach((to, from, next) => {
  const { user, token } = store.state
  const { requiredLogin, redirectAlreadyLogin } = to.meta
  if (!user.isLogin) {
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store.dispatch('fetchCurrentUser').then(() => {
        if (redirectAlreadyLogin) {
          next('/')
        } else {
          next()
        }
      }).catch(e => {
        console.error(e)
        store.commit('logout')
        next('login')
      })
    } else {
      if (requiredLogin) {
        next('/login')
      } else {
        next()
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      next('/')
    } else {
      next()
    }
  }
})

// 导出 router
export default router
